#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

vector<short> temps[1024];

int main(int argc, char const *argv[])
{
    int t, n, a, w, *result, size;
    int i, j;

    size = 0;
    temps[1] = { 1 };
    temps[2] = { 1 };
    for (i = 2; i <= 1000; i++)
    {
        for (j = 0; j < temps[i].size(); j++)
        {
            temps[i][j] *= i;
        }
        for (j = 0; j < temps[i].size() - 1; j++)
        {
            temps[i][j + 1] += temps[i][j] / 10;
            temps[i][j] %= 10;
        }
        w = temps[i][temps[i].size() - 1] / 10;
        temps[i][temps[i].size() - 1] %= 10;
        while (w)
        {
            temps[i].push_back(w % 10);
            w /= 10;
        }
        temps[i + 1] = vector<short>(temps[i].size());
        temps[i + 1].assign(temps[i].begin(), temps[i].end());        
        // for (j = 0; j < temps[i].size(); j++)
        // {
        //     cout << temps[i][j];
        // }
        // cout << "\n";
        size += sizeof(temps[i]);
    }
    cout << size / 1024;
    cin >> t;
    result = new int[t];
    for (i = 0; i < t; i++)
    {
        cin >> n >> a;
        result[i] = 0;
        for (j = 0; j < temps[n].size(); j++)
        {
            if (temps[n][j] == a)
            {
                result[i]++;
            }
        }
        cout << result[i] << "\n";
    }
    
    return 0;
}
